﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;

namespace LuaLanguageExtension.Intellisense
{
    [Export(typeof(ICompletionSourceProvider))]
    [ContentType("LuaLanguageExtension")]
    [Name("LuaCompletion")]
    class LuaCompletionSourceProvider : ICompletionSourceProvider
    {
        public ICompletionSource TryCreateCompletionSource(ITextBuffer textBuffer)
        {
			LuaLanguageExtension.Common.IMyExportClass cl = this.MyClass;
			cl.MyProperty = "Yess!!!!";
			return new LuaCompletionSource(textBuffer);
        }

		[Import]
		internal LuaLanguageExtension.Common.IMyExportClass MyClass { get; set; }

        [Import]
        internal ITextStructureNavigatorSelectorService NavigatorService { get; set; }
    }

    class LuaCompletionSource : ICompletionSource
    {
        private ITextBuffer buffer;
        private bool disposed = false;

        public LuaCompletionSource(ITextBuffer buf)
        {
            buffer = buf;
        }

        public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
        {
            if (disposed) throw new ObjectDisposedException("LuaCompletionSource");
			
            List<Completion> completions = new List<Completion>()
            {
                new Completion("Ook!"),
                new Completion("Ook."),
                new Completion("Ook?")
            };

            ITextSnapshot snapshot = buffer.CurrentSnapshot;
            var triggerPoint = (SnapshotPoint)session.GetTriggerPoint(snapshot);

            if (triggerPoint == null)
                return;

            var line = triggerPoint.GetContainingLine();
            SnapshotPoint start = triggerPoint;

            while (start > line.Start && !char.IsWhiteSpace((start - 1).GetChar()))
            {
                start -= 1;
            }

            var applicableTo = snapshot.CreateTrackingSpan(new SnapshotSpan(start, triggerPoint), SpanTrackingMode.EdgeInclusive);

            completionSets.Add(new CompletionSet("All", "All", applicableTo, completions, Enumerable.Empty<Completion>()));
        }

        public void Dispose()
        {
            disposed = true;
        }
    }
}
